#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
管理页面路由模块

提供简单的HTML管理界面
"""

from typing import Optional
from fastapi import APIRouter, Request, Form, HTTPException, Depends, status
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pathlib import Path

from ...models.user import WebDAVUser, WebDAVUserRepository
from ...common.database import get_sqlalchemy_manager
from ...common.unified_logging import get_logger


# 创建路由器
admin_router = APIRouter()

# 基本认证
security = HTTPBasic()

# 日志记录器
logger = get_logger('Admin')

# 模板配置
templates_dir = Path(__file__).parent / "templates"
if templates_dir.exists():
    templates = Jinja2Templates(directory=str(templates_dir))
else:
    templates = None


# 依赖注入
def get_user_repository() -> WebDAVUserRepository:
    """获取用户仓库"""
    db_manager = get_sqlalchemy_manager()
    session = db_manager.get_session()
    return WebDAVUserRepository(session)


def get_current_user(
    credentials: HTTPBasicCredentials = Depends(security),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
) -> WebDAVUser:
    """获取当前用户"""
    user = user_repo.authenticate(credentials.username, credentials.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Basic"},
        )
    return user


def render_template_or_html(template_name: str, context: dict) -> HTMLResponse:
    """渲染模板或返回简单HTML"""
    if templates:
        return templates.TemplateResponse(template_name, context)
    else:
        # 简单的HTML响应
        return HTMLResponse(_get_simple_html(template_name, context))


def _get_simple_html(template_name: str, context: dict) -> str:
    """获取简单HTML内容"""
    if template_name == "admin/index.html":
        return _get_admin_index_html(context)
    elif template_name == "admin/users.html":
        return _get_users_html(context)
    elif template_name == "admin/user_form.html":
        return _get_user_form_html(context)
    else:
        return "<html><body><h1>页面未找到</h1></body></html>"


def _get_admin_index_html(context: dict) -> str:
    """管理首页HTML"""
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>WebDAV管理面板</title>
        <meta charset="utf-8">
        <style>
            body {{ font-family: Arial, sans-serif; margin: 20px; }}
            .container {{ max-width: 1200px; margin: 0 auto; }}
            .nav {{ background: #f5f5f5; padding: 10px; margin-bottom: 20px; }}
            .nav a {{ margin-right: 20px; text-decoration: none; color: #333; }}
            .nav a:hover {{ color: #007bff; }}
            .card {{ border: 1px solid #ddd; padding: 20px; margin: 10px 0; }}
            .btn {{ padding: 8px 16px; background: #007bff; color: white; 
                   text-decoration: none; border-radius: 4px; }}
            .btn:hover {{ background: #0056b3; }}
        </style>
    </head>
    <body>
        <div class="container">
            <h1>WebDAV管理面板</h1>
            
            <div class="nav">
                <a href="/admin/">首页</a>
                <a href="/admin/users">用户管理</a>
                <a href="/admin/status">服务状态</a>
                <a href="/api/v1/docs">API文档</a>
                <a href="/">返回首页</a>
            </div>
            
            <div class="card">
                <h2>服务概览</h2>
                <p><strong>当前用户:</strong> {context.get('current_user', {}).get('username', 'N/A')}</p>
                <p><strong>服务状态:</strong> 运行中</p>
                <p><strong>WebDAV路径:</strong> /dav/</p>
            </div>
            
            <div class="card">
                <h2>快速操作</h2>
                <a href="/admin/users" class="btn">管理用户</a>
                <a href="/admin/users/create" class="btn">创建用户</a>
                <a href="/api/v1/docs" class="btn">查看API</a>
            </div>
        </div>
    </body>
    </html>
    """


def _get_users_html(context: dict) -> str:
    """用户管理页面HTML"""
    users = context.get('users', [])
    users_html = ""
    
    for user in users:
        status_badge = "✅" if user.is_active else "❌"
        users_html += f"""
        <tr>
            <td>{user.username}</td>
            <td>{status_badge} {'活跃' if user.is_active else '禁用'}</td>
            <td>{user.created_at.strftime('%Y-%m-%d %H:%M') if user.created_at else 'N/A'}</td>
            <td>
                <a href="/admin/users/{user.username}/edit" class="btn-small">编辑</a>
                <a href="/admin/users/{user.username}/delete" class="btn-small btn-danger" 
                   onclick="return confirm('确定要删除用户 {user.username} 吗？')">删除</a>
            </td>
        </tr>
        """
    
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>用户管理 - WebDAV管理面板</title>
        <meta charset="utf-8">
        <style>
            body {{ font-family: Arial, sans-serif; margin: 20px; }}
            .container {{ max-width: 1200px; margin: 0 auto; }}
            .nav {{ background: #f5f5f5; padding: 10px; margin-bottom: 20px; }}
            .nav a {{ margin-right: 20px; text-decoration: none; color: #333; }}
            .nav a:hover {{ color: #007bff; }}
            table {{ width: 100%; border-collapse: collapse; }}
            th, td {{ padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }}
            th {{ background-color: #f5f5f5; }}
            .btn {{ padding: 8px 16px; background: #007bff; color: white; 
                   text-decoration: none; border-radius: 4px; }}
            .btn:hover {{ background: #0056b3; }}
            .btn-small {{ padding: 4px 8px; font-size: 12px; }}
            .btn-danger {{ background: #dc3545; }}
            .btn-danger:hover {{ background: #c82333; }}
        </style>
    </head>
    <body>
        <div class="container">
            <h1>用户管理</h1>
            
            <div class="nav">
                <a href="/admin/">首页</a>
                <a href="/admin/users">用户管理</a>
                <a href="/admin/status">服务状态</a>
                <a href="/api/v1/docs">API文档</a>
                <a href="/">返回首页</a>
            </div>
            
            <div style="margin-bottom: 20px;">
                <a href="/admin/users/create" class="btn">创建新用户</a>
            </div>
            
            <table>
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {users_html}
                </tbody>
            </table>
        </div>
    </body>
    </html>
    """


def _get_user_form_html(context: dict) -> str:
    """用户表单页面HTML"""
    user = context.get('user')
    is_edit = user is not None
    title = "编辑用户" if is_edit else "创建用户"
    action = f"/admin/users/{user.username}/update" if is_edit else "/admin/users/create"
    
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>{title} - WebDAV管理面板</title>
        <meta charset="utf-8">
        <style>
            body {{ font-family: Arial, sans-serif; margin: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; }}
            .nav {{ background: #f5f5f5; padding: 10px; margin-bottom: 20px; }}
            .nav a {{ margin-right: 20px; text-decoration: none; color: #333; }}
            .nav a:hover {{ color: #007bff; }}
            .form-group {{ margin-bottom: 15px; }}
            label {{ display: block; margin-bottom: 5px; font-weight: bold; }}
            input[type="text"], input[type="password"] {{ 
                width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; 
            }}
            input[type="checkbox"] {{ margin-right: 5px; }}
            .btn {{ padding: 8px 16px; background: #007bff; color: white; 
                   border: none; border-radius: 4px; cursor: pointer; }}
            .btn:hover {{ background: #0056b3; }}
            .btn-secondary {{ background: #6c757d; }}
            .btn-secondary:hover {{ background: #545b62; }}
        </style>
    </head>
    <body>
        <div class="container">
            <h1>{title}</h1>
            
            <div class="nav">
                <a href="/admin/">首页</a>
                <a href="/admin/users">用户管理</a>
                <a href="/admin/status">服务状态</a>
                <a href="/api/v1/docs">API文档</a>
                <a href="/">返回首页</a>
            </div>
            
            <form method="post" action="{action}">
                <div class="form-group">
                    <label for="username">用户名:</label>
                    <input type="text" id="username" name="username" 
                           value="{user.username if is_edit else ''}" 
                           {'readonly' if is_edit else 'required'}>
                </div>
                
                <div class="form-group">
                    <label for="password">密码:</label>
                    <input type="password" id="password" name="password" 
                           {'placeholder="留空表示不修改密码"' if is_edit else 'required'}>
                </div>
                
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="is_active" value="true" 
                               {'checked' if not is_edit or user.is_active else ''}>
                        启用用户
                    </label>
                </div>
                
                <div class="form-group">
                    <button type="submit" class="btn">{'更新' if is_edit else '创建'}</button>
                    <a href="/admin/users" class="btn btn-secondary">取消</a>
                </div>
            </form>
        </div>
    </body>
    </html>
    """


# 路由定义
@admin_router.get("/", response_class=HTMLResponse)
async def admin_index(
    request: Request,
    current_user: WebDAVUser = Depends(get_current_user)
):
    """管理首页"""
    context = {
        "request": request,
        "current_user": {
            "username": current_user.username,
            "is_active": current_user.is_active
        }
    }
    return render_template_or_html("admin/index.html", context)


@admin_router.get("/users", response_class=HTMLResponse)
async def admin_users(
    request: Request,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """用户管理页面"""
    try:
        users = user_repo.find_all()
        context = {
            "request": request,
            "users": users,
            "current_user": current_user
        }
        return render_template_or_html("admin/users.html", context)
    except Exception as e:
        logger.error(f"获取用户列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取用户列表失败")


@admin_router.get("/users/create", response_class=HTMLResponse)
async def admin_user_create_form(
    request: Request,
    current_user: WebDAVUser = Depends(get_current_user)
):
    """创建用户表单"""
    context = {
        "request": request,
        "user": None,
        "current_user": current_user
    }
    return render_template_or_html("admin/user_form.html", context)


@admin_router.post("/users/create")
async def admin_user_create(
    username: str = Form(...),
    password: str = Form(...),
    is_active: Optional[str] = Form(None),
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """创建用户"""
    try:
        # 检查用户是否已存在
        existing_user = user_repo.find_by_username(username)
        if existing_user:
            raise HTTPException(status_code=400, detail="用户名已存在")
        
        # 创建新用户
        user_repo.create_user(
            username=username,
            password=password,
            is_active=is_active == "true"
        )
        
        return RedirectResponse(url="/admin/users", status_code=303)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建用户失败: {e}")
        raise HTTPException(status_code=500, detail="创建用户失败")


@admin_router.get("/users/{username}/edit", response_class=HTMLResponse)
async def admin_user_edit_form(
    username: str,
    request: Request,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """编辑用户表单"""
    try:
        user = user_repo.find_by_username(username)
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        context = {
            "request": request,
            "user": user,
            "current_user": current_user
        }
        return render_template_or_html("admin/user_form.html", context)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取用户信息失败")


@admin_router.post("/users/{username}/update")
async def admin_user_update(
    username: str,
    password: Optional[str] = Form(None),
    is_active: Optional[str] = Form(None),
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """更新用户"""
    try:
        user = user_repo.find_by_username(username)
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 更新密码
        if password and password.strip():
            user_repo.update_password(username, password)
        
        # 更新状态
        user_repo.update_status(username, is_active == "true")
        
        return RedirectResponse(url="/admin/users", status_code=303)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新用户失败: {e}")
        raise HTTPException(status_code=500, detail="更新用户失败")


@admin_router.get("/users/{username}/delete")
async def admin_user_delete(
    username: str,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """删除用户"""
    try:
        # 不能删除自己
        if username == current_user.username:
            raise HTTPException(status_code=400, detail="不能删除当前登录用户")
        
        user = user_repo.find_by_username(username)
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        user_repo.delete_user(username)
        
        return RedirectResponse(url="/admin/users", status_code=303)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除用户失败: {e}")
        raise HTTPException(status_code=500, detail="删除用户失败")


@admin_router.get("/status", response_class=HTMLResponse)
async def admin_status(
    request: Request,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """服务状态页面"""
    try:
        user_count = user_repo.count_active_users()
        
        status_html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>服务状态 - WebDAV管理面板</title>
            <meta charset="utf-8">
            <style>
                body {{ font-family: Arial, sans-serif; margin: 20px; }}
                .container {{ max-width: 800px; margin: 0 auto; }}
                .nav {{ background: #f5f5f5; padding: 10px; margin-bottom: 20px; }}
                .nav a {{ margin-right: 20px; text-decoration: none; color: #333; }}
                .nav a:hover {{ color: #007bff; }}
                .status-item {{ padding: 10px; margin: 10px 0; border-left: 4px solid #28a745; background: #f8f9fa; }}
                .status-item.warning {{ border-color: #ffc107; }}
                .status-item.error {{ border-color: #dc3545; }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1>服务状态</h1>
                
                <div class="nav">
                    <a href="/admin/">首页</a>
                    <a href="/admin/users">用户管理</a>
                    <a href="/admin/status">服务状态</a>
                    <a href="/api/v1/docs">API文档</a>
                    <a href="/">返回首页</a>
                </div>
                
                <div class="status-item">
                    <strong>WebDAV服务:</strong> 运行中 ✅
                </div>
                
                <div class="status-item">
                    <strong>API服务:</strong> 运行中 ✅
                </div>
                
                <div class="status-item">
                    <strong>用户数量:</strong> {user_count} 个活跃用户
                </div>
                
                <div class="status-item">
                    <strong>WebDAV路径:</strong> /dav/
                </div>
                
                <div class="status-item">
                    <strong>当前用户:</strong> {current_user.username}
                </div>
            </div>
        </body>
        </html>
        """
        
        return HTMLResponse(status_html)
    except Exception as e:
        logger.error(f"获取服务状态失败: {e}")
        raise HTTPException(status_code=500, detail="获取服务状态失败")